from flask import Blueprint,request,session,render_template
import BaseDao
blu=Blueprint("blog",__name__)

@blu.route('/blogs/<int:page>/', methods=['post', 'get'])  # 博客
def blogs(page):
    pagesize = 10
    sql = 'select * from blogs where status=1 order by id desc limit {},{}'.format((page-1)*pagesize,pagesize)
    sql2='select * from blogs where status=1'
    total_page=(len(BaseDao.select_db(sql2))//pagesize)+1
    if page == 0 or page == total_page + 1:
        return "<script type='text/javascript'>alert('没有更多了！');history.back()</script>"
    datas = BaseDao.select_db(sql)
    blogs_data = []
    for i in datas:
        blogs_data.append({'blog_id': i[0],
                           'title': i[1],
                           'date': i[2],
                           'tags': " ".join(i[3].split('&')),
                           #  "details":i[4],
                           # 'status':i[5],
                           'username': i[6]
                           })
    data = {'username': "未登录",
            'blogs_data': blogs_data,
            'Previous': page - 1,
            'now_page': page,
            'total_page':total_page,
            'Next': page + 1
            }
    if session.get("username"):
        data['username'] = session.get('username')
    return render_template('blogs.html', **data)


@blu.route('/search', methods=['post', 'get'])
def search():
    sql = ''
    BaseDao.select_db(sql)
    return "搜索结果数据"


@blu.route("/details/<int:id>/", methods=["get", "post"])
def details(id):
    sql = "select * from blogs where id=" + str(id)
    result = BaseDao.select_db(sql)
    data = {
        "title": result[0][1],
        "details": result[0][4],
        "user": result[0][6],
        "tags": result[0][3],
        "date": result[0][2]
    }
    return render_template("details.html", **data)